package com.ysw.wisdomcampus.fragment

import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ysw.wisdomcampus.R
import com.ysw.wisdomcampus.kt.glide
import com.ysw.wisdomcampus.model.projectModel
import com.ysw.wisdomcampus.model.tab.Student
import kotlinx.android.synthetic.main.fragment_performance.*
import org.litepal.LitePal


/**
 * A simple [Fragment] subclass.
 * Use the [MyPerformanceFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class MyPerformanceFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_performance, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        recycler_view.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = XAdapter()
        }
    }

    class XAdapter: RecyclerView.Adapter<XAdapter.Vh>() {
        class Vh(view: View): RecyclerView.ViewHolder(view) {
            fun bind(position: Int) {
                LitePal.findAll(Student::class.java)[position].apply {
                    itemView.findViewById<TextView>(R.id.name).text = name
                    itemView.findViewById<TextView>(R.id.xuehao).text = studentId
                    glide(
                        itemView.context,
                        resId = if (sex == "男") R.drawable.nan else R.drawable.nv,
                        view = itemView.findViewById(R.id.sexPic)
                    )
                    itemView.setOnClickListener {
                        AlertDialog.Builder(itemView.context).apply {
                            setTitle("成 绩")
                            setMessage(" 学号: $studentId \n 姓名: $name \n 性别: $sex \n 专业: $major " +
                                    "\n 数学: $math \n 物理: $physics \n 英语: $english \n\n 总成绩 ${math.toInt() + physics.toInt() + english.toInt()}")
                            setPositiveButton("了解") {d, w -> d.dismiss()}
                            create()
                            show()
                        }
                    }
                }
            }

        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Vh = Vh(
            LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
        )

        override fun onBindViewHolder(holder: Vh, position: Int) {
            holder.bind(position)
        }

        override fun getItemCount() = LitePal.findAll(Student::class.java).size
    }
}